package com.common.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;

import java.util.Date;

/**
 * @create 2020-11-24 00:28
 * appJWT工具类
 */

public class AppJwtUtil {
    /*
      生产JWT的基础数据，可以写在配置文件中
    */
    //密钥，盐
    private static final String SECRET = "app";
    //签发人
    private static final String ISSUER = "ljw/wx";
    //过期时间
    private static final long EXPIRE = 1000 * 60 * 60;

    //生产token
    public static String create(String username) {
        //设置加密算法
        Algorithm algorithm = Algorithm.HMAC256(SECRET);
        //指定当前时间
        Date date = new Date();
        //指定过期时间
        Date expire = new Date(date.getTime() + EXPIRE);
        //创建JWT
        String jwt = JWT.create()
                .withIssuer(ISSUER)
                .withIssuedAt(date)
                .withExpiresAt(expire)
                .withClaim("username", username)
                .sign(algorithm);
        return jwt;
    }

    //校验
    public static boolean verify(String apptoken) {
        try {
            Algorithm algorithm = Algorithm.HMAC256(SECRET);
            //获取验证信息
            JWTVerifier jwtVerifier = JWT.require(algorithm).withIssuer(ISSUER).build();
            //验证
            jwtVerifier.verify(apptoken);
            //如果检验不通过会报错
            return true;
        } catch (RuntimeException e) {
            //校验失败，抛异常
            return false;
        }
    }

    //获取username
    public static String getUserName(String apptoken) {
        return JWT.decode(apptoken).getClaim("username").asString();
    }

    //判断是否到期
    public static boolean isExpire(String apptoken) {
        Date expiresAt = JWT.decode(apptoken).getExpiresAt();
        return new Date().after(expiresAt);
    }
}
